package com.inspectortime.webapp.inspector.scheduleRule;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.inspectortime.domain.Inspector;
import com.inspectortime.domain.ScheduleRule;
import com.inspectortime.util.CalendarUtil;

public class AddScheduleRuleController extends ScheduleRuleController {
	
	private static Log log = LogFactory.getLog(AddScheduleRuleController.class);

	public AddScheduleRuleController() {
		super();
	}
	
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		
		ScheduleRule scheduleRule =  factory.createScheduleRule();
		
		String startDay = request.getParameter("calStartDay");
		String startMonth = request.getParameter("calStartMonth");
		String startYear = request.getParameter("calStartYear");
		
		if (!StringUtils.isBlank(startDay) && !StringUtils.isBlank(startMonth) && !StringUtils.isBlank(startYear)) {
			Calendar startDate = CalendarUtil.createDayCalendar(Integer.parseInt(startYear), Integer.parseInt(startMonth), Integer.parseInt(startDay));
			scheduleRule.setStartDate(startDate);
		}
		
		scheduleRule.setAvailable(true);
		scheduleRule.setUnits(new int[0]);

		return scheduleRule;
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
		throws Exception {
		
		log.debug("AddScheduleRuleController.onSubmit");
		
		ScheduleRule newRule = (ScheduleRule) command;
		
		String inspectorId = request.getParameter("inspectorId"); 
		Inspector inspector = repository.loadInspector(inspectorId);
		
		inspector.getScheduleRules().add(newRule);
		inspector.save();
		
		ModelAndView mv = new ModelAndView(getSuccessView());
		if (newRule.getStartDate() != null) {
			mv.addObject("start", buildUrlStartDate(newRule.getStartDate()));
		}
		mv.addObject("msg", "addEditScheduleRule.rule.created");
		mv.addObject("inspectorId", request.getParameter("inspectorId"));
		return mv;
		
	}
	


}
